package com.weixin.gong.utils.reflect;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author weixin.gong
 * @date 15-11-26 下午4:56
 */
public class ReflectUtil {

    public static <T> T invokePrivateMethod(Class target, String methodName, Object... params)
            throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
        Object obj = target.newInstance();
        return invokePrivateMethod(obj, methodName, params);
    }

    @SuppressWarnings("unchecked")
    public static <T> T invokePrivateMethod(Object obj, String methodName, Object... params)
            throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
        Class[] paramTypes = new Class[params.length];
        for (int i = 0; i < params.length; i++) {
            paramTypes[i] = params[i].getClass();
        }
        Method method = obj.getClass().getDeclaredMethod(methodName, paramTypes);
        return (T)method.invoke(obj, params);
    }

    public static <T> T invokePublicMethod(Class target, String methodName, Object... params)
            throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
        Object obj = target.newInstance();
        return invokePublicMethod(obj, methodName, params);
    }

    @SuppressWarnings("unchecked")
    public static <T> T invokePublicMethod(Object obj, String methodName, Object... params)
            throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
        Class[] paramTypes = new Class[params.length];
        for (int i = 0; i < params.length; i++) {
            paramTypes[i] = params[i].getClass();
        }
        Method method = obj.getClass().getMethod(methodName, paramTypes);
        return (T)method.invoke(obj, params);
    }

    public static void main(String[] args) {

    }
}
